import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '../views/user/login/Login.vue'
import Register from '../views/user/register/Register.vue'
import Home from '../components/common/Home.vue'
import UserInfo from '../views/user/userinfo/UserInfo.vue'
import UserUpdate from '../views/user/userupdate/UserUpdate.vue'
import UserDelete from '../views/user/userdelete/UserDelete.vue'

// 检查是否已登录
const isAuthenticated = () => {
  return localStorage.getItem('token') !== null
}

// 检查用户角色
const getUserRole = () => {
  const userInfo = localStorage.getItem('userInfo')
  if (userInfo) {
    try {
      const user = JSON.parse(userInfo)
      return user.role || 'USER'
    } catch (e) {
      return 'USER'
    }
  }
  return 'USER'
}

// 路由守卫
const requireAuth = (to, from, next) => {
  if (isAuthenticated()) {
    // 检查权限：只有管理员可以访问首页
    if (to.path === '/' && getUserRole() !== 'ADMIN') {
      next('/user/info') // 普通用户重定向到用户信息页面
    } else {
      next()
    }
  } else {
    next('/login')
  }
}

const routes = [
  { path: '/login', name: 'Login', component: Login },
  { path: '/register', name: 'Register', component: Register },
  { path: '/', name: 'Home', component: Home, beforeEnter: requireAuth },
  { path: '/user/info', name: 'UserInfo', component: UserInfo, beforeEnter: requireAuth },
  { path: '/user/update/:id', name: 'UserUpdate', component: UserUpdate, beforeEnter: requireAuth },
  { path: '/user/delete', name: 'UserDelete', component: UserDelete, beforeEnter: requireAuth }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  // 如果访问的是登录页面或注册页面，不做自动跳转，保持原页
  if (to.path === '/login' || to.path === '/register') {
    next()
    return
  }
  
  // 检查是否已登录
  if (isAuthenticated()) {
    // 检查权限：只有管理员可以访问首页
    if (to.path === '/' && getUserRole() !== 'ADMIN') {
      next('/user/info') // 普通用户重定向到用户信息页面
    } else {
      next()
    }
  } else {
    // 未登录，强制跳转到登录页面
    next('/login')
  }
})

export default router